'use strict'

var crypto = require('crypto');

exports.randomID = function() {
    return crypto.createHash('sha1').update(crypto.randomBytes(20)).digest();
};

exports.decodeNodes = function(data) {
    var nodes = [];
    for (var i = 0; i + 26 <= data.length; i += 26) {
        nodes.push({
            nid: data.slice(i, i + 20),
            address: data[i + 20] + '.' + data[i + 21] + '.' +
                data[i + 22] + '.' + data[i + 23],
            port: data.readUInt16BE(i + 24)
        });
    }
    return nodes;
};

exports.genNeighborID = function(target, nid) {
    return  Buffer.concat([target.slice(0, 10), nid.slice(10)]);
}

exports.formatTime = function(aa, bb) {
    let a = new Date(), b = typeof bb !== 'string' ? 'yyyy-MM-dd HH:mm:ss' : bb
    if( typeof aa === 'number' ||
        (aa && typeof aa === 'object' && aa instanceof Date)) a = new Date(aa)
    else if(typeof aa === 'string') {
        if(isNaN(aa)) {
            a = new Date(aa)
            if(isNaN(a.getTime())) {
                a = new Date()
                b = aa
            }
        } else a = new Date(Number(aa))
    }
    let yyyy = a.getFullYear().toString()
    let yyy = yyyy.slice(yyyy.length - 3)
    let yy = yyyy.slice(yyyy.length - 2)
    let y = yyyy.slice(yyyy.length - 1)
    let M = a.getMonth() + 1
    let d = a.getDate()
    let H = a.getHours()
    let m = a.getMinutes()
    let s = a.getSeconds()
    let ms = a.getMilliseconds()
    let MM = M < 10 ? '0' + M : M
    let dd = d < 10 ? '0' + d : d
    let HH = H < 10 ? '0' + H : H
    let mm = m < 10 ? '0' + m : m
    let ss = s < 10 ? '0' + s : s
    let Q = Math.ceil(M / 3)
    let D = a.getDay()
    let F = new Date(yyyy, 0, 4)
    let fd = F.getDay()
    fd = fd === 0 ? 6 : fd - 1
    let W = Math.floor((a.getTime() - F.getTime() + fd * 86400000) / 604800000) + 1
    return b.replace(/y{1,4}|M{1,2}|d{1,2}|H{1,2}|ms|m{1,2}|s{1,2}|Q|D|W/g, a => eval(a))
}